package com.yougong.api.modules.customer.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yougong.api.enums.ErrorEnum;
import com.yougong.api.modules.customer.model.enums.RoleEnums;
import com.yougong.api.modules.customer.model.enums.StatusEnums;
import com.yougong.api.modules.customer.model.pojo.CusRoleUser;
import com.yougong.api.modules.customer.model.pojo.CusUser;
import com.yougong.api.modules.customer.service.CusRoleUserService;
import com.yougong.api.modules.customer.service.CusUserService;
import com.yougong.api.modules.customer.model.dto.WxUserDto;
import com.yougong.api.util.WxMaConfiguration;
import com.yougong.common.api.CommonResult;
import com.yougong.common.util.JsonUtils;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@RequestMapping("/wx/user")
public class WxMaUserController {
    @Resource
    private CusUserService userService;


    @Autowired
    private CusRoleUserService cusRoleUserService;


    static private String appid = "wxe2b085b139713fac";

    static private String secret = "bf17efd8d92c8cbdec703b4b6732e729";

//    static private String appid = "wx985b12bcad4c4d2f";
//
//    static private String secret = "ee502e1062ffb91e421161da52e4e9a4";

    /**
     * 登陆接口
     */
    @PostMapping("/login")
    public CommonResult login(@RequestBody WxUserDto userInfo) throws WxErrorException {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(userInfo.getLoginCode());
        String openid = session.getOpenid();
        String phone = /*"";*/getPhone(userInfo.getPhoneCode());

        LambdaQueryWrapper<CusUser> eq = new LambdaQueryWrapper<CusUser>().eq(CusUser::getOpenId, openid);
        CusUser one = userService.getOne(eq);
        if (Objects.isNull(one)){
            // 添加用户
            String nickName = userInfo.getNickName();
            CusUser cusUser = new CusUser();
            cusUser.setPhonenumber(phone);
            cusUser.setUsername(nickName);
            cusUser.setOpenId(openid);
            cusUser.setAvatar(userInfo.getAvatarUrl());
            cusUser.setCreateDt(LocalDateTime.now());
            cusUser.setStatus(StatusEnums.SUCCESS.getType());
            this.userService.save(cusUser);


            //保存用户角色表
            CusRoleUser cusRoleUser = new CusRoleUser();
            cusRoleUser.setRoleId(RoleEnums.ADMIN.getNum());
            cusRoleUser.setUserId(cusUser.getUuid());
            cusRoleUser.setCreatedTime(LocalDateTime.now());
            cusRoleUserService.save(cusRoleUser);

            StpUtil.login(one.getUuid(),new SaLoginModel().setTimeout(-1));
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

            Map<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("tokenInfo", tokenInfo);
            tokenMap.put("user",one);
            return CommonResult.success(tokenMap);
        }else {

            //账户冻结
            if (StatusEnums.FAIL.getType().equals(one.getStatus())){
                return CommonResult.failed(ErrorEnum.USERINFO_FREEZE);
            }

            //添加token信息
            StpUtil.login(one.getUuid(),new SaLoginModel().setTimeout(-1));
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

            Map<String, Object> tokenMap = new HashMap<>();
            tokenMap.put("tokenInfo", tokenInfo);
            tokenMap.put("user",one);
            return CommonResult.success(tokenMap);
        }

    }


    /**
    *  获取手机号
    * @date: 2022/4/15
    * @author: MuChen
    */
    private String getPhone(String phoneCode) {
        Map map = new HashMap();
        map.put("grant_type","client_credential");
        map.put("appId",appid);
        map.put("secret",secret);
        String s = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token", map);
        JSONObject jsonObj = new JSONObject(s);
        String access_token = jsonObj.get("access_token").toString();
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+access_token;
        Map map1 = new HashMap();
        map1.put("code", phoneCode);
        String result2 = HttpRequest.post(url)
                .header(Header.CONTENT_TYPE, "application/json")//头信息，多个头信息多次调用此方法即可
                .body(JsonUtils.toJson(map1))//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();
        JSONObject jsonObj1 = new JSONObject(result2);
        String phone = jsonObj1.getJSONObject("phone_info").get("phoneNumber").toString();
        return phone;
    }

    @GetMapping("/key")
    public CommonResult key() {
            return CommonResult.success(secret);
    }

}
